// src/components/WechatLoginButton.tsx
import React, { useState } from 'react';
import { IonButton, IonIcon, IonSpinner } from '@ionic/react';
import { logoWechat } from 'ionicons/icons';
import { WechatAuth } from '../services/wechatAuth';

const WechatLoginButton: React.FC = () => {
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    setLoading(true);
    try {
      const url = await WechatAuth.getLoginUrl();
      // 在移动端使用InAppBrowser打开
      if (window.cordova) {
        const inAppBrowser = (window as any).cordova.InAppBrowser;
        const browser = inAppBrowser.open(
          url,
          '_blank',
          'location=yes,hidden=no'
        );
        
        browser.addEventListener('loadstart', (event: any) => {
          if (event.url.includes('code=')) {
            browser.close();
            const urlParams = new URLSearchParams(event.url.split('?')[1]);
            const code = urlParams.get('code');
            const state = urlParams.get('state');
            if (code && state) {
              handleCallback(code, state);
            }
          }
        });
      } else {
        // 在Web端重定向
        window.location.href = url;
      }
    } catch (error) {
      console.error('微信登录失败:', error);
      setLoading(false);
    }
  };

  const handleCallback = async (code: string, state: string) => {
    try {
      const result = await WechatAuth.handleCallback(code, state);
      // 保存token到localStorage
      localStorage.setItem('accessToken', result.accessToken);
      localStorage.setItem('refreshToken', result.refreshToken);
      
      // 获取用户信息
      const userInfo = await WechatAuth.getUserInfo(result.accessToken);
      console.log('用户信息:', userInfo);
      
      // 这里可以触发登录成功事件或重定向
      window.location.href = '/profile';
    } catch (error) {
      console.error('处理回调失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <IonButton 
      expand="block" 
      color="wechat" 
      onClick={handleLogin}
      disabled={loading}
    >
      {loading ? (
        <IonSpinner name="crescent" />
      ) : (
        <>
          <IonIcon slot="start" icon={logoWechat} />
          微信登录
        </>
      )}
    </IonButton>
  );
};

export default WechatLoginButton;